<?php
namespace app\home\controller;
use app\home\logic\Tuling;

/**
 * 用户控制器
 * 包括用户中心，用户登录及注册
 */
class Robot extends Home {
    public function _initialize(){
		if ( !is_login() ) {
			$this->error( '您还没有登陆',url('User/login') );
		}
	}
    function detail($id = 0){
        if (\think\Request::instance()->isGet()){
            $robot = \think\Db::name('f_tuling')->find($id);
            if(!$robot){
                $this->error("不存在的机器人！");
            }
            $tuling = new Tuling();
            $robotConfig = $tuling->find($robot['apikey']);
            $this->assign('robot', $robot);
            $this->assign('tulingRobotConfig', $robotConfig);
            return $this->fetch();
        }
       
        return $this->fetch();
    }

    function createRebot($type = 0){
        if (\think\Request::instance()->isGet()){
            $this->error("不支持的操作！");
        }
        $tuling = new Tuling();
        $ret = $tuling->CreateRobot(0);
        if($ret['code'] != 0){
            return json(['code'=>1, 'msg'=>'机器人创建失败！', 'data'=>$ret]);
        }
        //保存进数据库
        $data['name'] = "";
        $data['type'] = $type;
        $data['apikey'] = $ret['data']['apikey'];
        $data['rank'] = 1;
        $data['uid'] = is_login();

        $id = \think\Db::name("f_tuling")->insertGetId($data);
        if($id){
            $data['id'] = $id;
            return json(['code'=>0, 'msg'=>'机器人创建成功！', 'data'=>$data]);
        }
        return json(['code'=>1, 'msg'=>'机器人保存失败！', 'data'=>$data]);
    }

}